import React, { useEffect, useState } from "react";
import { MinusOutlined, PlusOutlined } from "@ant-design/icons";
import type { MenuProps } from "antd";
import { Button, Dropdown, Space, theme } from "antd";
import { MenuButton } from "./MenuButton.tsx";

const { useToken } = theme;

const items: MenuProps["items"] = [];
const Size = ({ size }: { size: number }) => {
  return (
    <span
      style={{
        lineHeight: "10px",
        width: 35,
        display: "inline-block",
        overflow: "hidden",
        textAlign: "center",
      }}
    >
      {size}%
    </span>
  );
};
export const ViewSize: React.FC = () => {
  const { token } = useToken();
  const [scale, setScale] = useState(100);
  let min = 10;
  let max = 1000;
  const scaleSubscriber = (val: number) => {
    setScale(Math.round(val * 100));
  };
  useEffect(() => {
    const timer = setTimeout(() => {
      if (window.meta2d) {
        clearTimeout(timer);
        // 获取初始缩放比例
        scaleSubscriber(window.meta2d.store.data.scale);
        // 监听缩放
        window.meta2d.on("scale", (num) => {
          scaleSubscriber(num);
        });
      }
    }, 200);
    return () => {
      if (timer) {
        clearTimeout(timer);
      }
    };
  }, []);
  const contentStyle: React.CSSProperties = {
    backgroundColor: token.colorBgElevated,
    borderRadius: token.borderRadiusLG,
    boxShadow: token.boxShadowSecondary,
  };
  const onScaleDefault = () => {
    window.meta2d.scale(1);
    window.meta2d.centerView();
  };

  const onScaleWindow = () => {
    window.meta2d.fitView();
  };

  const magnify = () => {
    if (scale >= min) {
      let scaleNum = scale - 10;
      setScale((v) => v - 10);
      window.meta2d.scale(scaleNum / 100);
    }
  };
  const shrink = () => {
    if (scale <= max) {
      let scaleNum = scale + 10;
      setScale((v) => v + 10);
      window.meta2d.scale(scaleNum / 100);
    }
  };
  return (
    <Dropdown
      arrow
      menu={{ items }}
      dropdownRender={() => (
        <div style={contentStyle}>
          <Space style={{ padding: 8 }}>
            <Button onClick={magnify}>
              <MinusOutlined />
            </Button>
            <Button onClick={shrink}>
              <PlusOutlined />
            </Button>
            <Button onClick={onScaleWindow} type={"primary"}>
              窗口大小
            </Button>
            <Button onClick={onScaleDefault} type={"primary"}>
              重置
            </Button>
          </Space>
        </div>
      )}
    >
      <a onClick={(e) => e.preventDefault()}>
        <MenuButton
          title={"视图"}
          arrow
          children={<Size size={scale} />}
        ></MenuButton>
      </a>
    </Dropdown>
  );
};
